#include "pch.h"
#include "Database.h"
#include <time.h>

CDbObjectId CreateDbObjId(CDbObjectPtr pDbObj)
{
	unsigned long id = long(pDbObj.get());
	
	return id + clock();
}

CDbObjectId CDatabase::AddToDb(CDbObjectPtr pDbObj, bool bClosedIfAdded)
{
	if (pDbObj)
		return CDbObjectId::kInvalid;

	CDbObjectId id = CreateDbObjId(pDbObj);
	auto iter = m_mapIdToDbobj.find(id);
	if (iter == m_mapIdToDbobj.end())
	{
		m_mapIdToDbobj.insert(std::make_pair(id, pDbObj));
		return id;
	}
	else
	{
		return AddToDb(pDbObj, bClosedIfAdded);
	}
}

CDbObjectPtr CDatabase::Open(const CDbObjectId& id, DbOpen type)
{
	CDbObjectPtr pobj(nullptr);
	Open(id, type, pobj);

	return pobj;
}

ResultType CDatabase::Open(const CDbObjectId& id, DbOpen type, CDbObjectPtr& ptr)
{
	auto iter = m_mapIdToDbobj.find(id);
	if (iter == m_mapIdToDbobj.end())
		return ResultType::eInvalidInput;

	CDbObjectPtr pObj(iter->second);
	switch (type)
	{
	case DbOpen::eForRead:
	{
		++(pObj->m_readSize);
		if (pObj->m_readSize >= 255)
			return ResultType::eHasOpenMaxReadCount;

		break;
	}
	case DbOpen::eForWrite:
	{
		if (pObj->m_writeSize == 0)
		{
			++(pObj->m_writeSize);
		}
		else
		{
			return ResultType::eHasOpenForWrite;
		}
		break;
	}
	default:
		return ResultType::eInvalidKey;
	}

	return ResultType::eOK;
}
